import { autoUpdater } from 'electron-updater'
import { ipcMain } from 'electron'
import db from '../datastore'
const path = require('path')
const log = require('electron-log')
log.transports.console.level = false
log.transports.console.level = 'silly'

let uploadUrl = db.read().get("trades.ttnew").value();
console.log('uploadUrl', uploadUrl)
// const uploadUrl = 'http://192.168.0.201/lb2/'

let timer = null
export default function updateHandle (mainWindow) {
  let message = {
    error: 'error',
    checking: 'checking',
    updateAva: 'updateAva',
    updateNotAva: 'updateNotAva'
  }

  clearInterval(timer)
  timer = setTimeout(() => {
    if (!uploadUrl) {
      uploadUrl = db.read().get("trades.ttnew").value();
      updateHandle(mainWindow)
    } else {
      console.log('更新地址' + uploadUrl)
      autoUpdater.setFeedURL(uploadUrl)
    }
    clearInterval(timer)
  }, 500)

  autoUpdater.on('error', function () {
    sendUpdateMessage(mainWindow, message.error)
  })

  // 事件：checking-for-update检查是否有版本更新
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage(mainWindow, message.checking)
  })

  // 事件：update-available有版本更新
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage(mainWindow, message.updateAva)
  })

  // 事件：update-not-available未发现更新版本
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage(mainWindow, message.updateNotAva)
  })

  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    mainWindow.webContents.send('downloadProgress', progressObj)
  })

  // 事件：updated-downloaded更新资源下载完毕
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log('开始更新')
      // some code here to handle event
      autoUpdater.quitAndInstall()
    })

    mainWindow.webContents.send('isUpdateNow')
  })
  ipcMain.on('checkForUpdate', () => {
    console.log('执行自动更新检查')
    // 执行自动更新检查
    // if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
    autoUpdater.checkForUpdates()
  })
}

function sendUpdateMessage (mainWindow, text) {
  mainWindow.webContents.send('message', text)
}
